<template>
	<view class="px-2 py-4">
		<wd-message-box />
		<wd-toast />
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, computed } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import * as LeaveApi from '@/api/bpm/leave'
import { getUserProfile } from "@/api/system/user/profile";
import { useMessage, useToast } from 'wot-design-uni'
import { formatDate, parseDateToTimestamp, getTodayZeroTimestamp, getTomorrowZeroTimestamp } from '@/utils/formatTime'



const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)
const resubmit = ref(0)
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)

// 指定审批人
const processDefineKey = 'oa_leave' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules

// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	attachments: []
})
//表单项字段配置

const formFields = ref<any[]>([

	{
		type: 'input',
		prop: 'applicantName',
		label: '申请人',
		placeholder: '请输入申请人',
		readonly: true,
	},
	{
		type: 'input',
		prop: 'applicationDept',
		label: '申请部门',
		placeholder: '请输入申请部门',
		readonly: true
	},
	{
		type: 'select',
		prop: 'type',
		label: '请假类型',
		placeholder: '请选择请假类型',
		filterable: true,
		clearable: true,
		options: getIntDictOptions(DICT_TYPE.BPM_OA_LEAVE_TYPE),
	},
	{
		type: 'datetime',
		prop: 'startTime',
		label: '开始时间',
		placeholder: '请选择开始时间',
		datetimeType: 'datetime',
	},
	{
		type: 'datetime',
		prop: 'endTime',
		label: '结束时间',
		placeholder: '请选择结束时间',
		datetimeType: 'datetime',
	},
	{
		type: 'textarea',
		prop: 'reason',
		label: '原因',
		placeholder: '请输入请假原因',
	},
	{
		type: 'upload',
		prop: 'attachments',
		label: '附件',
		placeholder: '上传附件',
		action: globalConfig.uploadUrl,
		limit: 1,
		accept: 'all',
		drag: true,
		header: headerObj.value,   // 如果有 token 或 header，你自己确认 headerObj.value 是否需要
		targetMapping: {
			fileUrl: 'attachments',
			fileName: 'ename'
		},
	},
])
const formData = ref<LeaveApi.LeaveVO>({
} as any)
const formRules = reactive({
	applicantName: [
		{ required: true, message: '请选择申请人', trigger: 'change' }
	],
	applicationDept: [
		{ required: true, message: '请选择申请部门', trigger: 'change' }
	],
	type: [{ required: true, message: '请假类型不能为空', trigger: 'blur' }],
	reason: [{ required: true, message: '请假原因不能为空', trigger: 'change' }],
	startTime: [{ required: true, message: '请假开始时间不能为空', trigger: 'change' }],
	endTime: [{ required: true, message: '请假结束时间不能为空', trigger: 'change' }],
	file: [{ required: true, message: '请上传文件', trigger: 'change' }]
})


onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
	const userProfile: any = await getUserProfile()

	formData.value.applicantId = userProfile.id
	formData.value.applicantName = userProfile.nickname
	formData.value.applicationDept = userProfile.dept.name
})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await LeaveApi.getLeave(Number(detailId.value))
		formData.value = data
		if (formData.value.startTime) {
			formData.value.startTime = parseDateToTimestamp(formData.value.startTime)
		}
		if (formData.value.startTime) {
			formData.value.endTime = parseDateToTimestamp(formData.value.endTime)
		}
		// 附件字段回显
		fileLists.value.attachments = buildFileList(data.attachments) as any;
		console.log('formData.value', formData.value);
	} catch (error) {
		console.log('加载数据失败')
	}
}




/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	try {
		if (type === 'update') {
			await LeaveApi.updateLeave(data)
			toast.success('编辑成功');
		} else {
			await LeaveApi.createLeave(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/bpm/oa/leave/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/bpm/oa/leave/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>